package com.sutong.client.interceptor;

import cn.hutool.core.util.RandomUtil;
import com.sutong.client.config.Key;
import com.sutong.common.utils.Constant;
import com.sutong.common.utils.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * 请求拦截器，添加签名、时间戳等请求头
 *
 * @author sutong
 * @date 2024-07-15 13:39
 */
@Slf4j
public class SignHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    public static ThreadLocal<Key> KEY = new ThreadLocal<>();


    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // tranceRequest(request, body);
        String bodyStr = new String(body, StandardCharsets.UTF_8);
        String signature = SignUtils.signature(KEY.get().getSecretKey(), request, bodyStr);
        // 一定不能直接带上 secretKey
        request.getHeaders().add(Constant.ACCESS_KEY, KEY.get().getAccessKey());
        request.getHeaders().add(Constant.SIGNATURE, signature);
        request.getHeaders().add(Constant.NONCE, RandomUtil.randomNumbers(4));
        request.getHeaders().add(Constant.TIMESTAMP, String.valueOf(System.currentTimeMillis()));
        ClientHttpResponse response = execution.execute(request, body);
        KEY.remove();
        // traceResponse(response);
        return response;
    }

    private void tranceRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException {
        log.debug("=========================== request begin ===========================");
        log.debug("uri : {}", request.getURI());
        log.debug("method : {}", request.getMethod());
        log.debug("headers : {}", request.getHeaders());
        log.debug("request body : {}", new String(body, StandardCharsets.UTF_8));
        log.debug("============================ request end ============================");
    }

    private void traceResponse(ClientHttpResponse httpResponse) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getBody(), StandardCharsets.UTF_8));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        log.debug("============================ response begin ============================");
        log.debug("Status code  : {}", httpResponse.getStatusCode());
        log.debug("Status text  : {}", httpResponse.getStatusText());
        log.debug("Headers      : {}", httpResponse.getHeaders());
        log.debug("Response body: {}", inputStringBuilder.toString());
        log.debug("============================= response end =============================");
    }

}
